package com.gxuwz.weather.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;

public class ApkDownloader {
    private static final String TAG = "ApkDownloader";
    private static final String TOKEN = "c80b6e76998c5fe6bd03ada2ba6c22a2";
    
    private Context context;
    private DownloadManager downloadManager;
    private long downloadId;
    private OnDownloadListener listener;
    
    public interface OnDownloadListener {
        void onDownloadStart();
        void onDownloadComplete(String filePath);
        void onDownloadFailed(String error);
    }
    
    public ApkDownloader(Context context) {
        this.context = context;
        this.downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }
    
    public void setOnDownloadListener(OnDownloadListener listener) {
        this.listener = listener;
    }
    
    /**
     * 开始下载APK
     * @param downloadUrl 下载地址
     * @param fileName 文件名
     */
    public void startDownload(String downloadUrl, String fileName) {
        try {
            // 创建下载请求
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));

            // 添加授权头信息
            request.addRequestHeader("Authorization", TOKEN);
            
            // 下载到系统默认Download目录
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
            
            // 设置下载参数
            request.setTitle("天气APP更新");
            request.setDescription("正在下载新版本");
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
            request.setAllowedOverRoaming(false);
            
            // 开始下载
            downloadId = downloadManager.enqueue(request);
            
            if (listener != null) {
                listener.onDownloadStart();
            }
            
            // 注册下载完成广播
            registerDownloadReceiver();
            
        } catch (Exception e) {
            Log.e(TAG, "开始下载失败", e);
            if (listener != null) {
                listener.onDownloadFailed("开始下载失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 注册下载完成广播接收器
     */
    private void registerDownloadReceiver() {
        BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (id == downloadId) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(downloadId);

                    android.database.Cursor cursor = downloadManager.query(query);
                    if (cursor.moveToFirst()) {
                        int statusColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        int localUriColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                        int reasonColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);

                        if (statusColumnIndex >= 0) {
                            int status = cursor.getInt(statusColumnIndex);

                            switch (status) {
                                case DownloadManager.STATUS_SUCCESSFUL:
                                    if (localUriColumnIndex >= 0) {
                                        String filePath = cursor.getString(localUriColumnIndex);
                                        if (listener != null) {
                                            listener.onDownloadComplete(filePath);
                                        }
                                    } else {
                                        if (listener != null) {
                                            listener.onDownloadFailed("无法获取下载文件路径");
                                        }
                                    }
                                    break;

                                case DownloadManager.STATUS_FAILED:
                                    if (reasonColumnIndex >= 0) {
                                        int reason = cursor.getInt(reasonColumnIndex);
                                        if (listener != null) {
                                            listener.onDownloadFailed("下载失败，错误码: " + reason);
                                        }
                                    } else {
                                        if (listener != null) {
                                            listener.onDownloadFailed("下载失败，未知错误");
                                        }
                                    }
                                    break;

                                default:
                                    if (listener != null) {
                                        listener.onDownloadFailed("下载状态异常: " + status);
                                    }
                                    break;
                            }
                        } else {
                            if (listener != null) {
                                listener.onDownloadFailed("无法获取下载状态");
                            }
                        }
                    } else {
                        if (listener != null) {
                            listener.onDownloadFailed("下载记录不存在");
                        }
                    }
                    cursor.close();

                    // 注销广播接收器
                    context.unregisterReceiver(this);
                }
            }
        };

        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(downloadReceiver, filter);
    }
    
    /**
     * 安装APK
     * @param filePath APK文件路径
     */
    public void installApk(String filePath) {
        try {
            // 解析filePath为实际文件路径
            Uri uri = Uri.parse(filePath);
            File file;
            if ("file".equals(uri.getScheme())) {
                file = new File(uri.getPath());
            } else {
                // 兼容部分机型返回的不是file://
                file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), uri.getLastPathSegment());
            }
            if (file.exists()) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
//                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                }
                context.startActivity(intent);
            } else {
                if (listener != null) {
                    listener.onDownloadFailed("APK文件不存在");
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "安装APK失败", e);
            if (listener != null) {
                listener.onDownloadFailed("安装失败: " + e.getMessage());
            }
        }
    }
} 